//
//  HBProductCommitmentController.m
//  Xfdsh
//
//  Created by aa on 05/03/2018.
//  Copyright © 2018 金刚葫芦娃. All rights reserved.
//

#import "HBProductCommitmentController.h"
#import <WebKit/WebKit.h>
#import "WYWebProgressLayer.h"

@interface HBProductCommitmentController ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate>
{
    WYWebProgressLayer *_progressLayer;
}
@property (nonatomic, strong) WKWebView * webView;
@property (nonatomic, strong) UIScrollView * scrollView;
@end

@implementation HBProductCommitmentController
- (void)dealloc
{
    self.webView.navigationDelegate = nil;
    [self.webView removeFromSuperview];
    self.webView = nil;
    self.webView.scrollView.delegate = nil;
    [_progressLayer closeTimer];
    [_progressLayer removeFromSuperlayer];
    _progressLayer = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
// 释放scrollView 强引用！！
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.webView.scrollView.delegate = nil;
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.title = self.title;
    WKWebView * webview = [[WKWebView alloc] init];
    _progressLayer = [WYWebProgressLayer new];
    if ([PublickFunctionObject isX]) {
        webview.frame = CGRectMake(0, -[UIApplication sharedApplication].statusBarFrame.size.height, APP_WIDTH, APP_HEIGHT+[UIApplication sharedApplication].statusBarFrame.size.height);
        webview.navigationDelegate = self;
        webview.scrollView.delegate = self;
        [self.view addSubview:webview];
        [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
        self.webView = webview;
        _progressLayer.frame = CGRectMake(0, 0, APP_WIDTH, 2);
    }else{
        webview.frame = CGRectMake(0, -20,APP_WIDTH,APP_HEIGHT+20);
        webview.navigationDelegate = self;
        webview.scrollView.delegate = self;
        [self.view addSubview:webview];
        [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
        self.webView = webview;
        _progressLayer.frame = CGRectMake(0,0, APP_WIDTH, 2);
    }
    [_webView.layer addSublayer:_progressLayer];
    [_webView setNeedsLayout];
    [self backButton];
    _button = [[UIButton alloc] init];
    [_button setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    _button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [_button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    _button.bounds = CGRectMake(0, 0, 35, 35);
    _button.titleLabel.font = [UIFont systemFontOfSize:15];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_button];
}
- (void)backButton
{
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame = CGRectMake(10, [UIApplication sharedApplication].statusBarFrame.size.height+20, 20, 20);
    [_button setBackgroundImage:[UIImage imageNamed:@"back_white.png"] forState:0];
    [_button setBackgroundColor:[UIColor clearColor]];
    [_button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    [webView evaluateJavaScript:@"document.getElementById(\"content\").offsetHeight;" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        //获取页面高度，并重置webview的frame
        CGFloat documentHeight = [result doubleValue];
        NSLog(@"高度 %f",documentHeight);
    }];
    [_progressLayer finishedLoad];
    [_progressLayer removeFromSuperlayer];
}
// WKNavigationDelegate 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [_progressLayer startLoad];
}
// WKNavigationDelegate 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    //navigationAction.request.URL.host
    NSLog(@"WKwebView ... didCommitNavigation ..");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:
(WKNavigationAction *)navigationAction decisionHandler:
(void (^)(WKNavigationActionPolicy))decisionHandler
{
#pragma mark == 每次点击按钮会触动这个方法
    NSString *urlString = [[navigationAction.request URL] absoluteString];
    urlString = [urlString stringByRemovingPercentEncoding];
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if ([urlComps count])
    {
        // 获取协议头
        NSString *protocolHead = [urlComps objectAtIndex:0];
        NSLog(@"protocolHead=%@",protocolHead);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
// WKNavigationDelegate 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [_progressLayer finishedLoad];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y > 100) {
        self.navigationItem.title = self.webView.title;
    }else{
        self.navigationItem.title = nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
